package org.dialMsg.Server.ServerImp;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import org.dialMsg.Pojo.BatchPostParam;
import org.dialMsg.Topic.UrlConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static org.dialMsg.Server.ServerImp.MyCryValue.getMyCryToken;

/**
 * @author DPF
 */
@Service
public class PostExampleHutoolBatch {
    private static final Logger logger = LoggerFactory.getLogger(PostExampleHutoolBatch.class);
    private static final String url = UrlConstants.BASE_URL + "/api/v1/robot/crm/post_contact_log";
    private static String myCryToken = null;

    static {
        int maxAttempts = 3;
        int attempt = 0;
        long baseDelayMs = 1000; // 基础等待时间1秒

        while (attempt < maxAttempts) {
            try {
                myCryToken = getMyCryToken("ccd");
                if (myCryToken != null) break; // 获取成功则退出
            } catch (Exception e) {
                logger.warn("第{}/{}次获取token失败: {}",
                        attempt + 1, maxAttempts, e.getMessage());
            }

            attempt++;
            if (attempt < maxAttempts) {
                try {
                    // 指数退避：每次等待时间翻倍（1s, 2s, 4s）
                    long sleepTime = baseDelayMs * (1 << (attempt - 1));
                    Thread.sleep(sleepTime);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    logger.warn("重试等待被中断", ie);
                    break;
                }
            }
        }

        if (myCryToken == null) {
            logger.error("获取myCryToken失败，已重试{}次", maxAttempts);
        }
    }

    /**
     * 逐条发送POST请求
     *
     * @param batchParams 参数列表
     * @return 所有响应的汇总
     */
    public String postBatchExample(List<BatchPostParam> batchParams) {
        if (batchParams.isEmpty()) {
            logger.warn("批量POST请求数据为空，跳过处理");
            return "批量数据为空";
        }


        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", myCryToken);
        headers.put("Content-Type", "application/json");

        int successCount = 0;
        int failCount = 0;
        List<String> failedIds = new ArrayList<>();

        // 逐条处理每个参数
        for (BatchPostParam param : batchParams) {
            if (param.getSource() == 1 || (param.getSource() == 2 && (param.getBridgeResult() == 0 || param.getBridgeResult() == 1 || param.getBridgeResult() == 5))) {
                logger.debug("过滤的条目，dialResultId: {}", param.getDialResultId());
                continue;
            }

            JSONObject singleData = new JSONObject();
            singleData.put("biz_id", param.getBizId());
            singleData.put("cont_child_state", param.getState());
            singleData.put("cont_content", "跟进备注+转接状态" + param.getBridgeResult() + "数据来源" + param.getSource());

            JSONObject contAttr = new JSONObject();
            contAttr.put("跟进标签", new String[]{"会到网点", "办理中"});
            contAttr.put("是否愿意调户", "是");
            singleData.put("cont_attr", contAttr.toJSONString());

            singleData.put("mobile", param.getMobile());
            singleData.put("cont_log_source", param.getSource());
            singleData.put("cont_time", param.getTime());
            singleData.put("cont_user", param.getUser());
            singleData.put("dial_result_id", param.getDialResultId());

            String requestBody = singleData.toJSONString();
            HttpResponse response = null;

            try {
                response = HttpRequest.post(url)
                        .addHeaders(headers)
                        .body(requestBody)
                        .execute();

                if (response.isOk() && response.getStatus() == 200) {
                    successCount++;
                } else {
                    logger.error("单条POST请求失败，状态码: {}", response.getStatus());
                    failCount++;
                    failedIds.add(String.valueOf(param.getDialResultId()));
                }
            } catch (Exception e) {
                logger.error("单条POST请求失败，dialResultId: {}，错误: {}",
                        param.getDialResultId(), e.getMessage(), e);
                failCount++;
                failedIds.add(String.valueOf(param.getDialResultId()));
            } finally {
                if (response != null) {
                    response.close();
                }
            }
        }

        // 返回处理结果统计信息
        return "处理完成。成功: " + successCount + "，失败: " + failCount +
                (failCount > 0 ? "，失败ID: " + String.join(",", failedIds) : "");
    }
}

class CacheDateFormatter {
    private static final Map<String, DateTimeFormatter> CACHE = new ConcurrentHashMap<>();

    public static DateTimeFormatter getFormatter(String pattern) {
        return CACHE.computeIfAbsent(pattern, DateTimeFormatter::ofPattern);
    }
}